<?php


namespace App\Server;

use Elasticsearch\Client;
use Elasticsearch\ClientBuilder;

class EsService
{
    private $es;

    //私有的静态属性（存放本类中唯一实例）
    private static $instance;

    //私有构造方法（防止类外实例化）
    private function __construct()
    {

    }

    //私有克隆方法（防止类外克隆并复制）
    private function __clone()
    {
        // TODO: Implement __clone() method.
    }

    //对外开放的唯一可以访问的公共方法
    public static function getInstance()
    {
        if (self::$instance)
        {
            return self::$instance;
        } else {
            self::$instance = new self();
            return self::$instance;
        }
    }

    /**
     * Name: 连接es
     * User: 王梓墨
     * Date: 2023/6/20
     * Time:10:54
     */
    public function client()
    {
        $host = ['127.0.0.1'];
        $client = ClientBuilder::create()
            ->setHosts($host)
            ->build();
        return $client;
    }

    //封装es 添加到es服务中
    public function esCreate($res){
//        dd($res->toArray());
        $params = [
            'index' => 'healthcare',
            'id'    => $res['id'],
            'type' => 'type',
            'body'  =>$res,
        ];
//        dd($params);
//        dd($res);
        $res = $this->client()->index($params);
//        dd($res);
        return $res;
    }

    //封装es服务搜索、高亮显示
    public function esSearch($name){
        $params = [
            'index' => 'healthcare',
            'body'  => [
                'query' => [
                    'match' => [
                        'name' => $name
                    ]
                ],
                'highlight' => [
                    'pre_tags' => ["<span style='color: #ff0000'>"],
                    'post_tags' => ["</span>"],
                    'fields' => [
                        "name" => new \stdClass()
                    ]
                ]
            ]
        ];

//        $results = $client->search($params);
        $results = $this->client()->search($params);
//        dd($results);
        $res=$results['hits']['hits'];
        foreach ($res as $k=>$v){
            $res[$k]['_source']['name']=$v['highlight']['name'][0];
        }
//        dd($res);
        return $res;
    }
}
